// 导入路径辅助模块，避免重复引用
const pathImport = require('../helpers/path_import.js');
const { pageHelper, cloudHelper, validate, ProjectBiz, FlowBiz, PassportBiz } = pathImport;

Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		isLoad: false,
		isEdit: false,

		id: '',
		cateId: '',
		cover: '',
		content: '',
		title: '',
		url: '',
		time: '',

		user: '', // 用户简介
		userDetail: {}, // user-simple-list按需传入

		flow: [], // 流程数据

		curCmt: '', //评论加载
		curIdxCmpt: -1, // 当前展开的评论索引

		showCheckModalFlag: false,
		curIdx: -1,

		formContent: '', //评论内容
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: async function (options) {
		ProjectBiz.initPage(this);

		// 强制设置登录状态
		FlowBiz.forceSetLoginState(this, 'flow_detail');

		if (!pageHelper.getOptions(this, options)) return;
		if (!options.id) return;

		this._loadDetail();
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () { 
		// 强制设置登录状态
		FlowBiz.forceSetLoginState(this, 'flow_detail');
	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () { 
		// 每次显示页面时强制设置登录状态
		FlowBiz.forceSetLoginState(this, 'flow_detail');
	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function () { },

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () { },

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: async function () {
		// 强制设置登录状态
		FlowBiz.forceSetLoginState(this, 'flow_detail');
		
		await this._loadDetail();
		wx.stopPullDownRefresh();
	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function () { },

	url: function (e) {
		// 强制设置登录状态
		FlowBiz.forceSetLoginState(this, 'flow_detail');
		
		pageHelper.url(e, this);
	},

	_loadDetail: async function () {
		// 强制设置登录状态
		FlowBiz.forceSetLoginState(this, 'flow_detail');
		
		try {
			let opts = {
				title: 'bar'
			}
			let params = {
				id: this.data.id
			}
			let flow = await cloudHelper.callCloudData('flow/detail', params, opts);

			//按照当前时间顺序倒序排
			let data = flow.FLOW_STEP;
			if (data && Array.isArray(data)) {
				data.reverse();
				flow.FLOW_STEP = data;
			} else {
				console.warn('FLOW_STEP为空或不是数组，设置为默认空数组');
				flow.FLOW_STEP = [];
			}

			if (flow) {
				// 确保所有字段都有默认值，避免undefined
				const setDataObj = {
					isLoad: true,
					flow,
					user: flow.FLOW_USER || '',
					title: flow.FLOW_TITLE || '',
					cover: flow.FLOW_CATE_NAME || '',
					cateId: flow.FLOW_CATE_ID || '',
					time: flow.FLOW_TITLE_TIME || ''
				};
				
				// 特别处理可能是undefined的嵌套属性
				if (flow.FLOW_OBJ) {
					setDataObj.url = flow.FLOW_OBJ_URL || '';
					setDataObj.content = flow.FLOW_OBJ_CONTENT || '';
				} else {
					setDataObj.url = '';
					setDataObj.content = '';
				}
				
				this.setData(setDataObj);
			} else {
				// 流程不存在的情况
				this.setData({
					isLoad: true,
					flow: null,
					user: '',
					title: '',
					cover: '',
					cateId: '',
					url: '',
					content: '',
					time: ''
				});
			}
		} catch (err) {
			console.log(err);
			
			// 错误情况也要设置默认值
			this.setData({
				isLoad: true,
				flow: null,
				user: '',
				title: '',
				cover: '',
				cateId: '',
				url: '',
				content: '',
				time: ''
			});
		}
	},

	bindBackTap: function (e) {
		// 强制设置登录状态
		FlowBiz.forceSetLoginState(this, 'flow_detail');
		
		wx.navigateBack({
			delta: 0,
		});
	},

	bindStepTap: function (e) {
		// 强制设置登录状态
		FlowBiz.forceSetLoginState(this, 'flow_detail');
		
		let id = this.data.id;
		let url = '../step/flow_step?id=' + id;
		wx.navigateTo({
			url,
		 timeout: 10000, fail: function(err) {
        // 处理超时错误
        if (err.errMsg && err.errMsg.includes("timeout")) {
          wx.showToast({
            title: "页面加载超时，请重试",
            icon: "none"
          });
          return;
        }
        
        // 处理其他错误
        console.error("页面跳转失败:", err);
        wx.showToast({
          title: "页面跳转失败",
          icon: "none"
        });
      }});
	},

	bindDelTap: async function (e) {
		// 强制设置登录状态
		FlowBiz.forceSetLoginState(this, 'flow_detail');
		
		let callback = async () => {
			let opts = {
				title: '删除中'
			}
			try {
				let params = {
					id: this.data.id
				}
				await cloudHelper.callCloud('flow/del', params, opts);
				pageHelper.showSuccToast('删除成功', 1500, function () {
					wx.navigateBack();
				});
			} catch (err) {
				console.log(err);
			}
		}
		pageHelper.showConfirm('您确认删除? 删除后不可恢复', callback);
	},

	bindEditTap: function (e) {
		// 强制设置登录状态
		FlowBiz.forceSetLoginState(this, 'flow_detail');
		
		let id = this.data.id;
		let cateId = this.data.cateId;
		if (!cateId) return;

		let title = encodeURIComponent(pageHelper.dataset(e, 'title'));
		let url = `../../../${this.data.url}?id=${id}&cateId=${cateId}&title=${title}`;
		wx.redirectTo({
			url,
		});
	},

	bindCmtTap: function (e) {
		// 强制设置登录状态
		FlowBiz.forceSetLoginState(this, 'flow_detail');
		
		let idx = pageHelper.dataset(e, 'idx');

		if (idx != this.data.curIdxCmpt) {
			this.setData({
				formContent: '',
				curIdxCmpt: idx
			});
		} else {
			this.setData({
				formContent: '',
				curIdxCmpt: -1
			});
		}
	},

	bindIptCmt: function (e) {
		// 强制设置登录状态
		FlowBiz.forceSetLoginState(this, 'flow_detail');
		
		this.setData({
			formContent: e.detail.value
		});
	},

	bindCmtSubmit: async function (e) {
		// 强制设置登录状态
		FlowBiz.forceSetLoginState(this, 'flow_detail');
		
		let formContent = this.data.formContent;
		if (validate.checkTextBlack(formContent).ret) {
			showError(validate.checkTextBlack(formContent).msg);
			return;
		}

		if (formContent.length > 10000) {
			showError('评论不能超过10000个字');
			return;
		}

		if (formContent.length < 5) {
			showError('评论不能少于5个字');
			return;
		}

		let params = {
			id: this.data.id,
			content: formContent,
			idx: this.data.curIdxCmpt,
		};

		let opts = {
			title: '评论中',
			cb: () => {
				this.setData({
					curIdxCmpt: -1,
					formContent: '',
				})
			}
		}
		try {
			await cloudHelper.callCloud('flow/comment', params, opts);
			this.setData({
				formContent: '',
				curIdxCmpt: -1,
			});
			this._loadDetail();
		} catch (e) {
			console.log(e);
		};
	},

	bindCancelCmtTap: function (e) {
		// 强制设置登录状态
		FlowBiz.forceSetLoginState(this, 'flow_detail');
		
		this.setData({
			formContent: '',
			curIdxCmpt: -1,
		});
	},

	bindShowCheckModalTap: function (e) {
		// 强制设置登录状态
		FlowBiz.forceSetLoginState(this, 'flow_detail');
		
		let idx = Number(pageHelper.dataset(e, 'idx'));

		this.setData({
			formContent: '',
			curIdx: idx,
			showCheckModalFlag: true
		});
	},

	bindHideCheckModalTap: function () {
		// 强制设置登录状态
		FlowBiz.forceSetLoginState(this, 'flow_detail');
		
		this.setData({
			showCheckModalFlag: false
		})
	},

	bindCheckTap: async function (e) {
		// 强制设置登录状态
		FlowBiz.forceSetLoginState(this, 'flow_detail');
		
		this.setData({
			formContent: '',
			curIdxCmpt: -1
		});

		let curIdx = pageHelper.dataset(e, 'idx');
		this.setData({
			showCheckModalFlag: true,
			curIdx
		});
	},

	bindHideCheckTap: function (e) {
		// 强制设置登录状态
		FlowBiz.forceSetLoginState(this, 'flow_detail');
		
		this.setData({
			showCheckModalFlag: false,
			curIdx: -1
		});
	},

	bindStatusAgreeTap: async function (e) {
		// 强制设置登录状态
		FlowBiz.forceSetLoginState(this, 'flow_detail');
		
		this.setData({
			showCheckModalFlag: false
		});

		let idx = this.data.curIdx;
		if (idx < 0) return;
		let callback = async () => {
			let opts = {
				title: '处理中'
			}
			try {
				let params = {
					id: this.data.id,
					idx
				}
				await cloudHelper.callCloud('flow/step_ok', params, opts);
				pageHelper.showSuccToast('处理成功', 1500);
				await this._loadDetail();

			} catch (err) {
				console.log(err);
			}
		}
		pageHelper.showConfirm('确认要通过此步骤审批?', callback);
	},

	bindStatusNoTap: async function (e) {
		// 强制设置登录状态
		FlowBiz.forceSetLoginState(this, 'flow_detail');
		
		this.setData({
			showCheckModalFlag: false
		});

		let idx = this.data.curIdx;
		if (idx < 0) return;

		let callback = async function () {
			let content = '';
			wx.showLoading({
				title: '请填写审批说明',
				icon: 'none'
			});

			let opts = {
				title: '请填写审批说明',
				content: '',
				type: 'textarea',
				rules: [{
					name: 'content',
					rule: 'required|string|min:10|max:500',
					msg: '请输入10-500字符审批说明'
				}]
			}
			content = await pageHelper.showModal(opts);
			if (!content || !content.content) return;

			wx.showLoading({
				title: '处理中',
				icon: 'none'
			});
			try {
				let params = {
					id: this.data.id,
					idx,
					content: content.content
				}
				let res = await cloudHelper.callCloud('flow/step_no', params, {});
				pageHelper.showSuccToast('处理成功', 1500);
				await this._loadDetail();
				
			} catch (err) {
				console.log(err);
			}
		}
		pageHelper.showConfirm('确认要打回此步骤审批?', callback.bind(this));
	},

	bindShowCancel: function(e) {
		// 强制设置登录状态
		FlowBiz.forceSetLoginState(this, 'flow_detail');
		
		let callback = async () => {
			try {
				let params = {
					id: this.data.id 
				}
				let opts = {
					title: '取消中'
				}
				await cloudHelper.callCloud('flow/cancel', params, opts);
				pageHelper.showSuccToast('取消成功', 1500);
				await this._loadDetail();
				
			} catch (err) {
				console.log(err);
			}
		}
		pageHelper.showConfirm('确认取消此流程?', callback);
	},

	bindDelFileTap: async function (e) {
		// 强制设置登录状态
		FlowBiz.forceSetLoginState(this, 'flow_detail');
		
		try {
			let that = this;
			let callback = async function () {
				let idx = pageHelper.dataset(e, 'idx');
				let fileidx = pageHelper.dataset(e, 'fileidx');

				let params = {
					id: that.data.id,
					idx,
					fileidx
				}
				await cloudHelper.callCloud('flow/file_del', params, {});
				pageHelper.showSuccToast('删除成功');

				await that._loadDetail();
			}
			pageHelper.showConfirm('确认删除此文件?', callback);
		} catch (err) {
			console.log(err);
		}
	},

	bindOpenFileTap: async function (e) {
		// 强制设置登录状态
		FlowBiz.forceSetLoginState(this, 'flow_detail');
		
		let url = pageHelper.dataset(e, 'url');
		try {
			wx.showLoading({
				title: '文件打开中',
				mask: true
			});
			const res = await wx.downloadFile({
				url,
			});
			if (res.statusCode === 200)
				await wx.openDocument({
					filePath: res.tempFilePath,
					showMenu: false
				});
		} catch (err) {
			console.error(err);
		} finally {
			wx.hideLoading();
		}

	}

})